#include <reg52.h>
#include <..\XC51.h>

unsigned char f = 0;
unsigned char Im[4] = {0x00, 0x00, 0x00, 0x00};
unsigned char show[2] = {0, 0};
unsigned long m, Tc;
unsigned char IrOK;

unsigned char pwm_left_val = 170;
unsigned char pwm_right_val = 170;
unsigned char pwm_t;

void FindRoad();
void AvoidBox();

void timer0() interrupt 1
{
	pwm_t++;
	if(pwm_t == 255)
		pwm_t = EN1 = EN2 = 0;
	if(pwm_left_val == pwm_t)
		EN1 = 1;		
	if(pwm_right_val == pwm_t)
		EN2 = 1;			 
}

void intersvr1(void) interrupt 2 using 1
{
  Tc = TH0 * 256 + TL0;
  TH0 = 0;
  TL0 = 0;
	
  if ((Tc > Imin) && (Tc < Imax))
  {
    m = 0;
    f = 1;
    return;
  }

  if (f == 1)
  {
    if (Tc > Inum1 && Tc < Inum3)
    {
      Im[m / 8] = Im[m / 8] >> 1 | 0x80;
      m++;
    }
    if (Tc > Inum2 && Tc < Inum1)
    {
      Im[m / 8] = Im[m / 8] >> 1;
      m++;
    }
    if (m == 32)
    {
      m = 0;
      f = 0;
      if (Im[2] == ~Im[3])
      {
        IrOK = 1;
      }
      else
        IrOK = 0;
    }
  }
}


int main(void)
{
  
  m = 0;
  f = 0;
  IT1 = 1;
  EX1 = 1;
  TMOD = 0x11;
  TH0 = 0;
  TL0 = 0;
  TR0 = 1;
  EA = 1;

  while (1)
  {
		EN1 = EN2 = 1;
    if (IrOK == 1)
    {
      switch (Im[2])
      {
      case 0x18:
        FindRoad();
        break;
      case 0x52:
        AvoidBox();
        break;

      default:
        break;
      }
      IrOK = 0;
    }
  }
}

void FindRoad()
{
	TMOD |= 0x02;
	TH0 = 220;
	TL0 = 220;
	TR0 = 1;
	ET0 = 1;
	EA	= 1;
	while(1)
	{
		if (key1 == 0)
		{
			delay(2);
			if (key1 == 0)
				AvoidBox();
		}
		if (left_find == 0 && right_find == 0)
		{
			advance();
		}
		else
		{
			if (left_find == 1 && right_find == 0)
			{
				left_turn();
			}
			if (left_find == 0 && right_find == 1)
			{
				right_turn();
			}
		}
		if (left_find == 1 && right_find == 1)
		{
			stop();
		}
	}
}

void AvoidBox()
{
	TMOD |= 0x02;
	TH0 = 220;
	TL0 = 220;
	TR0 = 1;
	ET0 = 1;
	EA	= 1;
	while(1)
	{
		if (key2 == 0)
		{
			delay(2);
			if (key2 == 0)
				FindRoad();
		}
		if (left_dodge == 0 && right_dodge == 0)
		{
			stop();
		}
		if (left_dodge == 1 && right_dodge == 0)
		{
			left_turn();
		}
		if (left_dodge == 0 && right_dodge == 1)
		{
			right_turn();
			
		}
		if (left_dodge == 1 && right_dodge == 1)
		{
			advance();
			
		}
	}
}